package com.macro.mall.portal.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.map.MapUtil;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsMessage;
import com.macro.mall.portal.common.MallEnum;
import com.macro.mall.portal.dao.MessageDao;
import com.macro.mall.portal.domain.FreindsResult;
import com.macro.mall.portal.domain.UserMessageDetail;
import com.macro.mall.portal.dto.ConversationsDto;
import com.macro.mall.portal.dto.MessageDto;
import com.macro.mall.portal.dto.UserDetailDto;
import com.macro.mall.portal.dto.UserNoReadCoutDto;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.service.UmsMessageService;
import com.macro.mall.portal.util.DateUtil;
import com.macro.mall.security.service.impl.RedisServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jsqlparser.statement.execute.Execute;
import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@Api(tags = "UmsMessageController", description = "会员消息管理")
@RequestMapping("/message")
public class UmsMessageController {


    @Autowired
    private UmsMessageService umsMessageService;

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private RedisServiceImpl redisService;

    @Value("{redis.key.conversations}")
    private String conversationskey;

    @ApiOperation("获取会员未读消息列表")
    @RequestMapping(value = "/noread/list", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getNoReadList(@RequestParam("fromuserIds") List<String> fromuserIds) {
        String userId=umsMemberService.getCurrentUser().getUserid();
        List<UserNoReadCoutDto> userNoReadCoutList=umsMessageService.getUserNoReadCountList(fromuserIds,userId) ;
        return CommonResult.success(userNoReadCoutList);
    }

    @ApiOperation("获取会员未读消息总数")
    @RequestMapping(value = "/noread/count", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getNoReadCount() {
        String userId=umsMemberService.getCurrentUser().getUserid();
        Integer count=umsMessageService.getUserNoReadMessageCount(userId) ;
        return CommonResult.success(count);
    }

    @ApiOperation("添加用户会话")
    @RequestMapping(value = "/conversations/add", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult addConversations(@RequestParam String friendId) {
        String userId=umsMemberService.getCurrentUser().getUserid();
        redisService.hSet(conversationskey+userId,friendId,0);
        return CommonResult.success(0);
    }

    @ApiOperation("移除用户会话")
    @RequestMapping(value = "/conversations/remove", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult removeConversations(@RequestParam String friendId) {
        String userId=umsMemberService.getCurrentUser().getUserid();
        redisService.hDel(conversationskey+userId,friendId);
        return CommonResult.success(0);
    }


    @ApiOperation("获取当前用户的所有会话")
    @RequestMapping(value = "/conversations/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getConversationsList() throws Exception {
        //Integer count=umsMessageService.getUserNoReadMessageCount(userId) ;
        String userId=umsMemberService.getCurrentUser().getUserid();
        Map friendIds= redisService.hGetAll(conversationskey+userId);
        List<ConversationsDto> conversationsDtoList=new ArrayList<ConversationsDto>();
        if(friendIds.size()==0)  return CommonResult.success(conversationsDtoList);
        List<String> friendIdList=new ArrayList<String>();
        for (Object obj :friendIds.keySet()){
            friendIdList.add(obj.toString());
        }
        //获取用户当前所有会话下所有的未读消息数
        List<UserNoReadCoutDto> userNoReadCoutList=umsMessageService.getUserNoReadCountList(friendIdList,userId) ;

        //获取用户当前所有会话的最后一条消息
        List<UmsMessage> lastMessageList=umsMessageService.getUserLastMessage(friendIdList,userId);

        //获取用户当前所有会话用户的信息
        List<UserDetailDto> userDetailList=umsMemberService.getUserDetail(friendIdList);

        for (String friendId :friendIdList){
            ConversationsDto cs=new ConversationsDto();
            UserNoReadCoutDto noReadCoutDto=userNoReadCoutList.stream().filter(s->friendId.equals(s.getFromuserId())).findAny().orElse(null);
            UmsMessage lastMessage=lastMessageList.stream()
                    .filter(s->(friendId.equals(s.getFromuserid())&&userId.equals(s.getTouserid()))||(userId.equals(s.getFromuserid())&&friendId.equals(s.getTouserid())))
                    .sorted(Comparator.comparing(UmsMessage::getCreatetime).reversed())
                    .findFirst().orElse(null);
            UserDetailDto userDetail=userDetailList.stream().filter(s->friendId.equals(s.getUserId())).findAny().orElse(null);
            Long timeStamp=DateUtil.dateToStamp(lastMessage==null?"":lastMessage.getCreatetime());
            cs.setContent(lastMessage==null?"":lastMessage.getMessagetext());
            cs.setConversationId(0);
            cs.setFriendHeadUrl(userDetail==null?"":userDetail.getAvatorUrl());
            cs.setFriendId(friendId);
            cs.setFriendName(userDetail==null?"":userDetail.getNickName());
            cs.setMsgUserId(userId);
            cs.setTimestamp(timeStamp);
            cs.setTimeStr(DateUtil.getShortTime(timeStamp));
            cs.setType(MallEnum.getValue(lastMessage==null?0:lastMessage.getMessagetype()));
            cs.setUnread(noReadCoutDto==null?0:noReadCoutDto.getNoreadCount());
            conversationsDtoList.add(cs);
        }
        return CommonResult.success(conversationsDtoList);
    }

    @ApiOperation("获取用户会话历史消息")
    @RequestMapping(value = "/conversations/historymessage", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getConversationsHistoryMessage(@RequestParam String friendId,
                                                        @RequestParam Integer pageIndex,
                                                        @RequestParam Integer pageSize) throws Exception {
        String userId=umsMemberService.getCurrentUser().getUserid();
        //获取头像路径
        List<String> userIds=new ArrayList<String>();
        userIds.add(userId);
        userIds.add(friendId);
        List<UserDetailDto> userDetailDtoList=umsMemberService.getUserDetail(userIds);
        UserDetailDto friendDetail =userDetailDtoList.stream().filter(s->friendId.equals(s.getUserId())).findAny().orElse(null);
        String friendAvatorUrl=friendDetail==null?"":friendDetail.getAvatorUrl();
        UserDetailDto userDetail =userDetailDtoList.stream().filter(s->userId.equals(s.getUserId())).findAny().orElse(null);
        String userAvatorUrl=userDetail==null?"":userDetail.getAvatorUrl();
        List<UmsMessage> umsMessageList=umsMessageService.getHistoryMessage(userId,friendId,pageIndex,pageSize);
        CommonPage<UmsMessage> pageList= CommonPage.restPage(umsMessageList);

        List<MessageDto> messageList=new ArrayList<MessageDto>();
        umsMessageList=umsMessageList.stream().sorted(Comparator.comparing(UmsMessage::getCreatetime)).collect(Collectors.toList());
        Date upCreateTime=null;
        for (int i=0;i<umsMessageList.size();i++){
            UmsMessage message=umsMessageList.get(i);
            Long timeStamp=DateUtil.dateToStamp(message.getCreatetime());
            Boolean isMy=message.getFromuserid().equals(userId);
            String avatorUrl=isMy?userAvatorUrl:friendAvatorUrl;
            Date createTime= cn.hutool.core.date.DateUtil.parseDateTime(message.getCreatetime());
            Long differHoure = cn.hutool.core.date.DateUtil.between(new Date(),createTime, DateUnit.HOUR);
            SimpleDateFormat formatter=new SimpleDateFormat(differHoure>24?"yyyy/MM/dd HH:mm:ss":"HH:mm");

            String dateString=formatter.format(createTime);

            Boolean isShowTime=true;
            if(upCreateTime!=null) {
                Long differMin = cn.hutool.core.date.DateUtil.between(upCreateTime, createTime, DateUnit.MINUTE);
                if (differMin < 5) {
                    isShowTime = false;
                }
            }

            MessageDto messageDto=new MessageDto();
            messageDto.setContent(message.getMessagetext());
            messageDto.setFriendId(friendId);
            messageDto.setTimestamp(timeStamp);
            messageDto.setType(MallEnum.getValue(message.getMessagetype()));
            messageDto.setHeadUrl(avatorUrl);
            messageDto.setIsMy(isMy);
            messageDto.setMsgId(message.getMessageid());
            messageDto.setSendStatus("success");
            messageDto.setTime(dateString);
            messageDto.setShowTime(isShowTime);
            messageDto.setIsPlaying(false);
            messageDto.setVoiceDuration(message.getDuration());
            messageList.add(messageDto);
            upCreateTime= cn.hutool.core.date.DateUtil.parseDateTime(message.getCreatetime());
        }

        return CommonResult.success(messageList);
    }


    @ApiOperation("更新用户会话消息已读状态")
    @RequestMapping(value = "/readstatus/update", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult updateMessageReadStatus(@RequestParam String friendId) {
        String userId=umsMemberService.getCurrentUser().getUserid();
        Integer count= umsMessageService.updateMessageReadStatus(userId,friendId);
        return CommonResult.success(count);
    }




}
